from db.admin_dao import AdminDao
from db.business_dao import BusinessDao

class AdminView:
    def __init__(self):
        self.admin_dao = AdminDao()
        self.business_dao = BusinessDao()

    def show_login(self):
        print("\n===============================")
        print("    饿了么后台管理系统登录    ")
        print("===============================")
        
        admin_name = input("请输入管理员名称：")
        password = input("请输入密码：")
        
        admin = self.admin_dao.login(admin_name, password)
        if admin:
            print(f"\n登录成功！欢迎，{admin.admin_name}！")
            self.show_main_menu()
        else:
            print("\n登录失败！管理员名称或密码错误！")
            if input("是否重新登录？(y/n): ").lower() == 'y':
                self.show_login()

    def show_main_menu(self):
        while True:
            print("\n===============================")
            print("1.所有商家列表 2.搜索商家 3.新建商家 4.删除商家 5.退出系统")
            print("===============================")
            
            try:
                choice = int(input("请输入你的选择："))
                
                if choice == 1:
                    self.list_all_businesses()
                elif choice == 2:
                    self.search_business()
                elif choice == 3:
                    self.create_business()  # 新建商家
                elif choice == 4:
                    self.delete_business()  # 删除商家
                elif choice == 5:
                    print("退出系统！")
                    break
                else:
                    print("无效的选择！")
            except ValueError:
                print("请输入有效的数字选项！")

    def list_all_businesses(self):
        businesses = self.business_dao.list_all()
        print("\n=== 商家列表 ===")
        print(f"{'编号':<8}{'名称':<30}{'地址':<30}{'起送费':<10}{'配送费':<10}")
        for biz in businesses:
            print(f"{biz.business_id:<8}{biz.business_name:<30}"
                  f"{biz.business_address[:25]+'...' if biz.business_address else '':<30}"
                  f"{biz.star_price:<10.2f}{biz.delivery_price:<10.2f}")
    
    def search_business(self):
        """
        搜索商家功能
        """
        print("\n===============================")
        print("        商家搜索功能")
        print("===============================")
        
        # 获取搜索条件
        search_term = input("请输入商家名称或ID进行搜索: ").strip()
        
        try:
            # 尝试按ID搜索
            business_id = int(search_term)
            business = self.business_dao.get_by_id(business_id)
            if business:
                self._display_business(business)
            else:
                print(f"未找到ID为 {business_id} 的商家")
        except ValueError:
            # 按名称搜索
            businesses = self.business_dao.search_by_name(search_term)
            if businesses:
                print("\n找到以下商家:")
                for business in businesses:
                    self._display_business(business)
            else:
                print(f"未找到名称包含 '{search_term}' 的商家")

    def _display_business(self, business):
        """
        显示单个商家信息（辅助方法）
        """
        print("\n商家信息:")
        print(f"ID: {business.business_id}")
        print(f"名称: {business.business_name}")
        print(f"地址: {business.business_address}")
        print(f"介绍: {business.business_explain}")
        print(f"起送费: {business.star_price}")
        print(f"配送费: {business.delivery_price}")
        print("-------------------------------")

    def create_business(self):
        """
        创建新商家
        """
        print("\n===============================")
        print("        新建商家")
        print("===============================")
        
        try:
            # 获取商家信息
            business_name = input("商家名称: ").strip()
            password = input("登录密码: ").strip()
            address = input("商家地址: ").strip()
            explain = input("商家介绍: ").strip()
            star_price = float(input("起送费(元): ").strip())
            delivery_price = float(input("配送费(元): ").strip())
            
            # 创建Business对象
            from entities.business import Business
            business = Business(
                business_id=None,  # ID由数据库自动生成
                password=password,
                business_name=business_name,
                business_address=address,
                business_explain=explain,
                star_price=star_price,
                delivery_price=delivery_price
            )
            
            # 调用DAO创建商家
            new_id = self.business_dao.create(business)
            print(f"\n商家创建成功！ID: {new_id}")
            
        except ValueError:
            print("输入格式错误，请确保金额输入正确！")
        except Exception as e:
            print(f"创建商家失败: {e}")

    def delete_business(self):
        """
        删除商家
        """
        print("\n===============================")
        print("        删除商家")
        print("===============================")
        
        # 先列出所有商家方便选择
        businesses = self.business_dao.list_all()
        if not businesses:
            print("当前没有商家可删除")
            return
        
        print("\n当前商家列表:")
        for biz in businesses:
            print(f"{biz.business_id}: {biz.business_name}")
        
        try:
            business_id = int(input("\n请输入要删除的商家ID: ").strip())
            
            # 确认删除
            confirm = input(f"确认删除ID为 {business_id} 的商家吗？(y/n): ").lower()
            if confirm == 'y':
                affected = self.business_dao.delete(business_id)
                if affected > 0:
                    print("商家删除成功！")
                else:
                    print("未找到指定ID的商家")
            else:
                print("取消删除操作")
                
        except ValueError:
            print("请输入有效的数字ID！")
        except Exception as e:
            print(f"删除商家失败: {e}")